package com.hu;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.hu.config.Config;
import com.hu.thread.WorkThread;
import com.hu.util.PropertiesUtils;
import jdk.nashorn.internal.objects.annotations.Getter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class InputFrame extends JFrame {
    private Box userInputBox;
    private Box buttonBox;//按钮盒子，包含登录和忘记密码两个按钮,水平排列
    private Box excelPathBox;
    private Box runCountBox;
    private Box proxyClickPosBox;

    private Integer runCount = 10;

    private Integer nowCount = 0;

    private List<String> usernameList = new ArrayList<>();

    private Iterator<String> iterableList;
    private Box ipBox;
    private JLabel excelPathLabel;
    private JLabel runCountLabel;
    private JLabel proxyClickPosLabel;
    private JLabel ipLabel;
    private JTextField excelPathInput;
    private JTextField runCountInput;
    private JTextField proxyClickPosInput;
    private JTextArea ipTextArea;
    private JTextArea logTextArea;
    private JButton excelPathSelectBtn;

    private String username;

    private JButton startBtn;//登录按钮
    private JButton sleepBtn;//忘记密码按钮
    private JButton goBtn;//忘记密码按钮
    private JButton saveBtn;//忘记密码按钮
    private Config config;

    private boolean isStop;

    private InputFrame frame;
    private String pos = "1000,400|1000,500|1000,600|1000,700|1000,800";

    public boolean isStop() {
        return isStop;
    }

    public void setStop(boolean stop) {
        isStop = stop;
    }

    public InputFrame() {

        config = new Config();
        frame = this;
        //实例化所有的对象
        excelPathLabel = new JLabel("excel路径");
        runCountLabel = new JLabel("运行次数");
        proxyClickPosLabel = new JLabel("点击坐标");
        ipLabel = new JLabel("代理IP");
        excelPathInput = new JTextField();
        excelPathInput.setEditable(false);
        excelPathInput.setColumns(10);
        runCountInput = new JTextField();
        runCountInput.setColumns(15);
        proxyClickPosInput = new JTextField();
        proxyClickPosInput.setColumns(15);
        ipTextArea = new JTextArea();
        ipTextArea.setRows(6);
        ipTextArea.setLineWrap(true);
        ipTextArea.setColumns(20);
        ipTextArea.setWrapStyleWord(true);
        logTextArea = new JTextArea();
        logTextArea.setLineWrap(true);
        logTextArea.setRows(18);
        logTextArea.setColumns(25);
        JScrollPane jsp = new JScrollPane(logTextArea);
        //设置矩形大小.参数依次为(矩形左上角横坐标x,矩形左上角纵坐标y，矩形长度，矩形宽度)
        jsp.setBounds(0, 0, 270, 400);
        //默认的设置是超过文本框才会显示滚动条，以下设置让滚动条一直显示
        jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);


        excelPathSelectBtn = new JButton("选择");
        startBtn = new JButton("开始");
        sleepBtn = new JButton("暂停");
        goBtn = new JButton("继续");
        saveBtn = new JButton("保存");

        userInputBox = Box.createVerticalBox();
        excelPathBox = Box.createHorizontalBox();//内部组件，垂直排列
        buttonBox = Box.createHorizontalBox();//内部组件，水平排列
        runCountBox = Box.createHorizontalBox();//内部组件，水平排列
        proxyClickPosBox = Box.createHorizontalBox();//内部组件，水平排列
        ipBox = Box.createHorizontalBox();//内部组件，水平排列

        excelPathBox.add(excelPathLabel);
        excelPathBox.add(Box.createHorizontalStrut(5));//输入框和label的横向间距
        excelPathBox.add(excelPathInput);
        excelPathBox.add(excelPathSelectBtn);

        runCountBox.add(runCountLabel);
        runCountBox.add(Box.createHorizontalStrut(5));//输入框和label的横向间距
        runCountBox.add(runCountInput);

        proxyClickPosBox.add(proxyClickPosLabel);
        proxyClickPosBox.add(Box.createHorizontalStrut(5));//输入框和label的横向间距
        proxyClickPosBox.add(proxyClickPosInput);

        ipBox.add(ipLabel);
        ipBox.add(Box.createHorizontalStrut(5));//输入框和label的横向间距
        ipBox.add(ipTextArea);

        userInputBox.add(excelPathBox);
        userInputBox.add(runCountBox);
        userInputBox.add(proxyClickPosBox);
        userInputBox.add(ipBox);

        //将两个按钮加入到按钮盒子
        buttonBox.add(Box.createHorizontalStrut(5));//第一个按钮和左边界的距离
        buttonBox.add(startBtn);
        buttonBox.add(Box.createHorizontalStrut(5));//两个按钮之间的间距
        buttonBox.add(sleepBtn);
        buttonBox.add(Box.createHorizontalStrut(5));//两个按钮之间的间距
        buttonBox.add(goBtn);
        buttonBox.add(Box.createHorizontalStrut(5));//两个按钮之间的间距
        buttonBox.add(saveBtn);
        //这个面板为空布局
        //设置这两个大盒子userInputBox和buttonBox的位置
        setLayout(null);
        setBounds(0, 0, 700, 400);//该窗口本身的位置和大小
        //加入这两个大Box

        JPanel jPanel1 = new JPanel();
        JPanel jPanel2 = new JPanel();
        JPanel jPanel3 = new JPanel();
        jPanel1.add(userInputBox);
        jPanel2.add(buttonBox);
        jPanel3.add(jsp);
        add(jPanel1,BorderLayout.CENTER);
        add(jPanel2,BorderLayout.SOUTH);
        add(jPanel3,BorderLayout.EAST);
        //设置这两个大Box的位置和大小
        jPanel1.setBounds(0, 0, 300, 210);
        jPanel2.setBounds(0, 250, 300, 100);
        jPanel3.setBounds(350, 0, 300, 400);
        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        validate();

    }

    public synchronized void refresh(){
        if(iterableList.hasNext() ){
            nowCount = 0;
            System.out.println("换下一个账号");
            username = iterableList.next();
            showLog("换账号:"+username);
        }
    }

    public synchronized String getUsername() {
        return username;
    }

    public void init(){
        excelPathInput.setText(PropertiesUtils.getKey("excelPath"));
        runCountInput.setText(PropertiesUtils.getKey("runCount"));
        ipTextArea.setText(PropertiesUtils.getKey("ipText"));
        String proxyClickPos = PropertiesUtils.getKey("proxyClickPos");
        proxyClickPosInput.setText(proxyClickPos);

        sleepBtn.setEnabled(false);
        goBtn.setEnabled(false);
        startBtn.setEnabled(true);
        saveBtn.setEnabled(true);

        saveBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                save();
             }
        });
        startBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showLog("脚本开始");
                startBtn.setEnabled(false);
                sleepBtn.setEnabled(true);
                goBtn.setEnabled(true);
                save();
                try {
                    Runtime.getRuntime().exec("taskkill /f /t /im chromedriver.exe");
                } catch (IOException ex) {
                    showLog("关闭之前浏览器驱动失败");
                    showLog(ex.getMessage());
                }

                int port = 20010;
                Thread thread = new WorkThread(frame,port);
                thread.start();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    System.out.println(ExceptionUtil.stacktraceToString(ex));
                }
            }
        });
        sleepBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showLog("脚本暂停");
                sleepBtn.setEnabled(false);
                goBtn.setEnabled(true);
                frame.setStop(true);
            }
        });
        goBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showLog("脚本继续");
                sleepBtn.setEnabled(true);
                goBtn.setEnabled(false);
                frame.setStop(false);
            }
        });

        excelPathSelectBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc=new JFileChooser("D:\\");
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);  //可以选择文件和文件夹
                int val=fc.showOpenDialog(null);
                if(val==fc.APPROVE_OPTION){
                    //正常选择文件
                    excelPathInput.setText(fc.getSelectedFile().toString());
                    config.setExcelPath(fc.getSelectedFile().toString());
                    PropertiesUtils.saveKey("excelPath", config.getExcelPath());
                }else{
                    //未正常选择文件，如选择取消按钮
                    excelPathInput.setText("未选择文件");
                }
            }
        });

    }

    public String getProxyClickPoses() {
        return proxyClickPosInput.getText();
    }

    public Config getConfig() {
        return config;
    }


    public void showLog(String msg){
        System.out.println(msg);
        String text = logTextArea.getText();
        text = text + msg +"\r\n";
        logTextArea.setText(text);
    }

    private void save(){

        config.setExcelPath(excelPathInput.getText());
        config.setRunCount(Integer.parseInt(runCountInput.getText()));
        config.setProxyClickPoses(proxyClickPosInput.getText());
        config.setIpText(ipTextArea.getText());

        File file = new File(config.getExcelPath());
        if(!file.exists()){
            showLog("未找到Excel文件!");
            return;
        }

        PropertiesUtils.saveKey("runCount", String.valueOf(config.getRunCount()));
        PropertiesUtils.saveKey("proxyClickPos", config.getProxyClickPoses());
        PropertiesUtils.saveKey("ipText", config.getIpText());


        runCount = Integer.parseInt(runCountInput.getText());
        String text = ipTextArea.getText();
        String[] split = text.split("\n");
        for (String s : split) {
            String[] split1 = s.split("@");
            usernameList.add(split1[0]);
        }

        iterableList = usernameList.iterator();
        username = iterableList.next();
    }
}
